package com.javabasic.algorithm.sword_of_offer;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see
 * @since Created by work on 2022/1/8 12:34 上午
 */
public class 剑指_Offer_53_在排序数组中查找数字一 {

    /**
     * 暴力遍历查找
     * @param nums
     * @param target
     * @return
     */
    public int search(int[] nums, int target) {
        int len = nums.length, result = 0;
        for (int i = 0; i < len; i++) {
            if (nums[i] == target) {
                result++;
            }
        }
        return result;
    }

    /**
     * 二分法求上下界
     * @param nums
     * @param target
     * @return
     */
    public int search2(int[] nums, int target) {
        int len = nums.length;
        int left = 0, right = len, mid;
        /**
         * 二分法求上界
         */
        while (left <= right) {
            mid = left + ((right-left)>>1);
            if (nums[mid] > target) {
                right = mid;
            } else {
                left = mid+1;
            }
        }
        System.out.println(left);
        int result = 0;
        for (int i = left-1; i >= 0; i--) {
            if (nums[i] == target) {
                result++;
            } else {
                break;
            }
        }
        return result;
    }
}
